package com.googlecode.pwlodars.piteststat.statistics;


import static com.google.common.base.Objects.firstNonNull;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.googlecode.pwlodars.piteststat.content.PackageInfo;
import com.googlecode.pwlodars.piteststat.content.PitestSingleResult;
import com.googlecode.pwlodars.piteststat.database.PitResultDao;

@RequestMapping(value="/statistics")
public class StatisticsControler {

	private PitResultDao pitResultDao;
	
	private AveragesCalculkator averagesCalculkator;
	
	public StatisticsControler(PitResultDao pitResultDao, AveragesCalculkator averagesCalculkator) {
		this.pitResultDao = pitResultDao;
		this.averagesCalculkator=averagesCalculkator;
	}


	@RequestMapping(method=GET)
	public String getStatistics(@RequestParam(value="packageId",required = false) Integer packageIdParam,Map<String, Object> model){
		Integer packageId = firstNonNull(packageIdParam, 0);

		PackageInfo currentPackage = pitResultDao.readPackageInfo(packageId);
		List<PackageInfo> childPackages = pitResultDao.readPackages(packageId);
		List<PackageStatisticsData> statistics = calculatePackageStatistics(childPackages);

		List<PitestSingleResult> packageClasses = pitResultDao.readResultsFromOnlyOnePackage(packageId);
		
		model.put("packageStatistics", statistics);
		model.put("packageClasses", packageClasses);
		model.put("currentPackage", currentPackage);
		return "statistics";
	}


	private List<PackageStatisticsData> calculatePackageStatistics(List<PackageInfo> childPackages) {
		List<PackageStatisticsData> statistics=new LinkedList<PackageStatisticsData>();
		for (PackageInfo packageInfo : childPackages) {
			List<PitestSingleResult> results = pitResultDao.readResultsFromPackageAndChildren(packageInfo.getId());
			int averageMutationCoverage = averagesCalculkator.calculateAverageMutationalCoverage(results);
			statistics.add(new PackageStatisticsData(packageInfo, averageMutationCoverage));
		}
		return statistics;
	}
	
	
	public static class PackageStatisticsData{
		private PackageInfo packageInfo;
		private int mutationCoverage;
		public PackageStatisticsData(PackageInfo packageInfo, int mutationCoverage) {
			this.packageInfo = packageInfo;
			this.mutationCoverage = mutationCoverage;
		}
		
		public PackageInfo getPackageInfo() {
			return packageInfo;
		}
		
		public int getMutationCoverage() {
			return mutationCoverage;
		}
		
	}
}
